package com.h4313.ghome.ui.dialog;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;

public class AccountPickerDialog extends DialogFragment {

	public interface AccountPickerCallback {
		public void onAccountPicked(Account account);
	}

	private AccountPickerCallback mCallback;

	public AccountPickerDialog() {
	}

	public AccountPickerDialog(AccountPickerCallback callback) {
		mCallback = callback;
	}

	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {

		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		builder.setTitle("Select a Google account");

		AccountManager accountManager = AccountManager.get(getActivity());
		final Account[] accounts = accountManager.getAccountsByType("com.google");
		
		final int size = accounts.length;
		String[] names = new String[size];

		for (int i = 0; i < size; i++) {
			names[i] = accounts[i].name;
		}

		builder.setItems(names, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				// Stuff to do when the account is selected by the user
				if (mCallback != null) {
					mCallback.onAccountPicked(accounts[which]);
				}
			}
		});
		return builder.create();

	}
}
